package com.ruoyi.tranShort.mqtt;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.tranShort.mqtt.exception.ResponseTimeOutException;


/**
 * @author wwy
 * @date 2021-08-10 16:23
 */
public class ResponseHandle {
    public static int timeOut = 2000;

    /**
     * 等待连接消息
     * @param mac
     * @return
     * @throws ResponseTimeOutException
     */
    public static String waitConnectMessage(String mac) throws ResponseTimeOutException {
        int i = 0;
        while (true){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //获取值
            String message = Subscribe.connectMap.get(mac);
            if(StringUtils.isNotEmpty(message)){
                Subscribe.connectMap.remove(mac);
                return message;
            }
            i++;
            if(200*i>=timeOut){
                throw new ResponseTimeOutException();
            }


        }
    }

    /**
     * 等待发送消息
     * @param mac
     * @return
     * @throws ResponseTimeOutException
     */
    public static String waitMessage(String mac) throws ResponseTimeOutException {
        int i = 0;
        while (true){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //获取值
            String message = Subscribe.passthroughMap.get(mac);
            if(StringUtils.isNotEmpty(message)){
                Subscribe.passthroughMap.remove(mac);
                return message;
            }
            i++;
            if(200*i>=timeOut){
                throw new ResponseTimeOutException();
            }


        }
    }

    /**
     * 等待连接消息
     * @param mac
     * @return
     * @throws ResponseTimeOutException
     */
    public static String waitCloseMessage(String mac) throws ResponseTimeOutException {
        int i = 0;
        while (true){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //获取值
            String message = Subscribe.closeMap.get(mac);
            if(StringUtils.isNotEmpty(message)){
                Subscribe.closeMap.remove(mac);
                return message;
            }
            i++;
            if(200*i>=timeOut){
                throw new ResponseTimeOutException();
            }

        }

    }
}
